<template>
  <div class="profile-container">
    <div class="page-header">
      <h1>个人中心</h1>
    </div>

    <el-row :gutter="20">
      <el-col :xs="24" :sm="8" :md="6">
        <el-card class="profile-card">
          <div class="profile-name">{{ doctorInfo.name || '未设置姓名' }}</div>
          <div class="profile-role">{{ doctorInfo.specialty || '未设置专业' }}</div>
          <el-divider />
          <div class="profile-stats">
            <div class="stat-item">
              <div class="stat-value">{{ patientCount }}</div>
              <div class="stat-label">管理患者</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ diagnosisCount }}</div>
              <div class="stat-label">诊断数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ workDays }}</div>
              <div class="stat-label">工作天数</div>
            </div>
          </div>
        </el-card>

        <el-card class="menu-card">
          <el-menu
            :default-active="activeMenu"
            class="profile-menu"
          >
            <el-menu-item index="basic-info" @click="activeTab = 'basic-info'">
              <el-icon><User /></el-icon>
              <span>基本信息</span>
            </el-menu-item>
            <el-menu-item index="security" @click="activeTab = 'security'">
              <el-icon><Lock /></el-icon>
              <span>账号安全</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="16" :md="18">
        <el-card class="content-card">
          <!-- 基本信息 -->
          <div v-if="activeTab === 'basic-info'">
            <div class="tab-header">
              <h2>基本信息</h2>
              <el-button type="primary" @click="handleEditBasicInfo">编辑信息</el-button>
            </div>
            
            <el-form label-position="right" label-width="120px" class="profile-form">
              <el-form-item label="姓名">
                <div>{{ doctorInfo.name || '未设置' }}</div>
              </el-form-item>
              <el-form-item label="专业领域">
                <div>{{ doctorInfo.specialty || '未设置' }}</div>
              </el-form-item>
              <el-form-item label="联系方式">
                <div>{{ doctorInfo.contact || '未设置' }}</div>
              </el-form-item>
              <el-form-item label="用户名">
                <div>{{ doctorInfo.username || '未设置' }}</div>
              </el-form-item>
            </el-form>
          </div>

          <!-- 账号安全 -->
          <div v-else-if="activeTab === 'security'">
            <div class="tab-header">
              <h2>账号安全</h2>
            </div>
            
            <div class="security-items">
              <div class="security-item">
                <div class="security-info">
                  <div class="security-title">登录密码</div>
                  <div class="security-description">定期修改密码可以保护账号安全</div>
                </div>
                <el-button @click="handleChangePassword">修改密码</el-button>
              </div>
              
              <el-divider />
              
              <div class="security-item">
                <div class="security-info">
                  <div class="security-title">手机验证</div>
                  <div class="security-description">已绑定手机: {{ doctorInfo.contact || '未设置' }}</div>
                </div>
                <el-button @click="handleChangePhone">修改手机</el-button>
              </div>
              
              <el-divider />
              
              <div class="security-item">
                <div class="security-info">
                  <div class="security-title">登录设备管理</div>
                  <div class="security-description">查看并管理已登录的设备</div>
                </div>
                <el-button @click="handleManageDevices">管理设备</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑基本信息对话框 -->
    <el-dialog
      title="编辑基本信息"
      v-model="editDialogVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="专业领域" prop="specialty">
          <el-input v-model="editForm.specialty" placeholder="请输入专业领域" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="editForm.contact" placeholder="请输入联系方式" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
      title="修改密码"
      v-model="passwordDialogVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="120px">
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入当前密码" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPasswordForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改手机对话框 -->
    <el-dialog
      title="修改手机号码"
      v-model="phoneDialogVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="phoneFormRef" :model="phoneForm" :rules="phoneRules" label-width="120px">
        <el-form-item label="当前手机号码">
          <div>{{ doctorInfo.contact || '未设置' }}</div>
        </el-form-item>
        <el-form-item label="新手机号码" prop="newPhone">
          <el-input v-model="phoneForm.newPhone" placeholder="请输入新手机号码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="phoneDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPhoneForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  User, 
  Lock
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { getDoctors, updateDoctors } from '@/api/doctors'
import { listPatients } from '@/api/patients'
import { listDoctordiagnoses } from '@/api/doctordiagnoses'

const userStore = useUserStore()
const activeTab = ref('basic-info')
const activeMenu = computed(() => activeTab.value)

// 医生信息
const doctorInfo = ref({})

// 统计数据
const patientCount = ref(0)
const diagnosisCount = ref(0)
const workDays = ref(0)

// 对话框控制
const editDialogVisible = ref(false)
const passwordDialogVisible = ref(false)
const phoneDialogVisible = ref(false)

// 编辑表单
const editFormRef = ref(null)
const editForm = reactive({
  id: null,
  name: '',
  specialty: '',
  contact: ''
})

// 密码表单
const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 手机表单
const phoneFormRef = ref(null)
const phoneForm = reactive({
  newPhone: ''
})

// 表单验证规则
const editRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  specialty: [{ required: true, message: '请输入专业领域', trigger: 'blur' }],
  contact: [{ required: true, message: '请输入联系方式', trigger: 'blur' }]
}

const passwordRules = {
  oldPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const phoneRules = {
  newPhone: [
    { required: true, message: '请输入新手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
}

// 获取医生信息
const getDoctorInfo = async () => {
  try {
    const doctorId = userStore.id
    if (!doctorId) {
      ElMessage.error('未找到医生ID，请重新登录')
      return
    }
    
    const response = await getDoctors(doctorId)
    doctorInfo.value = response
    
    // 初始化编辑表单
    editForm.id = response.id
    editForm.name = response.name
    editForm.specialty = response.specialty
    editForm.contact = response.contact
    
    // 获取统计数据
    await getStatistics(doctorId)
  } catch (error) {
    console.error('获取医生信息失败:', error)
    ElMessage.error('获取医生信息失败')
  }
}

// 获取统计数据
const getStatistics = async (doctorId) => {
  try {
    // 获取患者数量
    const patientsResponse = await listPatients()
    patientCount.value = patientsResponse.length
    
    // 获取诊断数量
    const diagnosesResponse = await listDoctordiagnoses({ doctorId })
    diagnosisCount.value = diagnosesResponse.length
    
    // 计算工作天数（简化处理，实际应从后端获取）
    const now = new Date()
    const startDate = new Date(now.getFullYear(), now.getMonth(), 1) // 本月第一天
    workDays.value = Math.floor((now - startDate) / (24 * 60 * 60 * 1000)) + 1
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 处理编辑基本信息
const handleEditBasicInfo = () => {
  editForm.id = doctorInfo.value.id
  editForm.name = doctorInfo.value.name
  editForm.specialty = doctorInfo.value.specialty
  editForm.contact = doctorInfo.value.contact
  editDialogVisible.value = true
}

// 提交编辑表单
const submitEditForm = () => {
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateDoctors(editForm)
        ElMessage.success('更新个人信息成功')
        editDialogVisible.value = false
        
        // 重新获取医生信息
        await getDoctorInfo()
      } catch (error) {
        console.error('更新个人信息失败:', error)
        ElMessage.error('更新个人信息失败')
      }
    }
  })
}

// 处理修改密码
const handleChangePassword = () => {
  // 重置表单
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = true
}

// 提交密码表单
const submitPasswordForm = () => {
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const updateData = {
          id: doctorInfo.value.id,
          password: passwordForm.newPassword
        }
        await updateDoctors(updateData)
        ElMessage.success('修改密码成功')
        passwordDialogVisible.value = false
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改密码失败')
      }
    }
  })
}

// 处理修改手机
const handleChangePhone = () => {
  // 重置表单
  phoneForm.newPhone = ''
  phoneDialogVisible.value = true
}

// 提交手机表单
const submitPhoneForm = () => {
  phoneFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const updateData = {
          id: doctorInfo.value.id,
          contact: phoneForm.newPhone
        }
        await updateDoctors(updateData)
        ElMessage.success('修改手机号码成功')
        phoneDialogVisible.value = false
        
        // 重新获取医生信息
        await getDoctorInfo()
      } catch (error) {
        console.error('修改手机号码失败:', error)
        ElMessage.error('修改手机号码失败')
      }
    }
  })
}

// 处理管理设备
const handleManageDevices = () => {
  ElMessage.info('设备管理功能开发中...')
}

// 生命周期钩子
onMounted(() => {
  getDoctorInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.profile-card {
  text-align: center;
  padding: 20px;
  margin-bottom: 20px;
}

.profile-name {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 5px;
}

.profile-role {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.profile-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 15px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 20px;
  font-weight: 500;
  color: #409EFF;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.menu-card {
  margin-bottom: 20px;
}

.profile-menu {
  border-right: none;
}

.content-card {
  min-height: 500px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.tab-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.profile-form {
  max-width: 600px;
}

.security-items {
  max-width: 600px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
}

.security-title {
  font-size: 16px;
  margin-bottom: 5px;
}

.security-description {
  font-size: 14px;
  color: #909399;
}
</style> 